package com.mail.service;

import com.mail.pojo.Mail;
import jakarta.annotation.Resource;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;


@Service
public class MailService {
	@Resource
	JavaMailSender javaMailSender;
	public void sendSimpleMailManager(Mail mail){
		System.out.println(mail);
		SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
		simpleMailMessage.setFrom(mail.getFrom());
		simpleMailMessage.setTo(mail.getTo());
		simpleMailMessage.setCc(mail.getCc());
		simpleMailMessage.setSubject(mail.getSubject());
		simpleMailMessage.setText(mail.getContent());
		javaMailSender.send(simpleMailMessage);
	}
	public void sendMailWithFile(Mail mail){
		try {
			MimeMessage mailMessage=javaMailSender.createMimeMessage();
			MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mailMessage, true);
			mimeMessageHelper.setFrom(mail.getFrom());
			mimeMessageHelper.setTo(mail.getTo());
			mimeMessageHelper.setCc(mail.getCc());
			mimeMessageHelper.setSubject(mail.getSubject());
			mimeMessageHelper.setText(mail.getContent());
			mimeMessageHelper.addAttachment(mail.getFile().getName(),mail.getFile());
			javaMailSender.send(mimeMessageHelper.getMimeMessage());
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}
	@Resource
	TemplateEngine templateEngine;
	public void sendTemplateMail(Mail mail,String username,String orderNo,String amount,String mobile){
		try {
			MimeMessage mimeMessage=javaMailSender.createMimeMessage();
			MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
			mimeMessageHelper.setFrom(mail.getFrom());
			mimeMessageHelper.setTo(mail.getTo());
			mimeMessageHelper.setCc(mail.getCc());
			mimeMessageHelper.setSubject(mail.getSubject());
			Context context=new Context();
			context.setVariable("username",username);
			context.setVariable("orderNo",orderNo);
			context.setVariable("amount",amount);
			context.setVariable("mobile",mobile);
			String content = templateEngine.process("templateMail.html", context);
			System.out.println(content);
			mimeMessageHelper.setText(content,true);
			javaMailSender.send(mimeMessageHelper.getMimeMessage());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
